package org.zqy.util;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * 分页工具类
 * 
 * @author ZQY
 * 
 */
public class Paging {

	/**
	 * 分页查询
	 * 
	 * @param hql
	 *            查询的条件
	 * @param offset
	 *            开始记录
	 * @param length
	 *            一次查询几条记录
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List queryForPage(final String hql, final int offset,
			final int length) {
		Session session = MySessionFactory.getSessionFactory().openSession();
		List list = null;
		try {
			session.beginTransaction();
			Query query = session.createQuery(hql);
			query.setFirstResult(offset);
			query.setMaxResults(length);
			list = query.list();
		} catch (Exception e) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			// 关闭session
			if (session != null && session.isOpen())
				session.close();
		}
		return list;

	}

	/**
	 * 查询所有记录数
	 * 
	 * @return 总记录数
	 */
	public static int getAllRowCount(String hql) {
		Session session = MySessionFactory.getSessionFactory().openSession();
		int i = 0;
		try {
			session.beginTransaction();
			Query query = session.createQuery(hql);
			i = query.list().size();
		} catch (Exception e) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			// 关闭session
			if (session != null && session.isOpen())
				session.close();
		}
		return i;
	}
}
